package com.gupao.mvcframework.v4.servlet;

import com.gupao.mvcframework.annotation.*;
import com.sun.xml.internal.ws.wsdl.writer.document.ParamType;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.net.URL;
import java.util.*;
import java.util.logging.Handler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GPDispatcherServlet extends HttpServlet {
    private Properties configContexts = new Properties();
    private List<String> classNames = new ArrayList<String>();
    private Map<String, Object> ioc = new HashMap<String, Object>();
    private List<Handler> handlerList = new ArrayList<Handler>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatcher(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception!!");
            e.printStackTrace();
        }
    }

    private void doDispatcher(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        Handler handler = getHandler(req);
        if(handler == null){
            resp.getWriter().write("404 NotFound!!!");
            return;
        }

        //获得handler所有的形参
        Class<?>[] paramTypes = handler.getParamTypes();

        Object[] paramValues = new Object[paramTypes.length];
        Map<String, String[]> parameterMap = req.getParameterMap();
        for(Map.Entry<String, String[]> entry : parameterMap.entrySet()){
            String value = Arrays.toString(entry.getValue()).replaceAll("\\[|\\]", "").replaceAll("\\s", "");
            if(!handler.paramIndexMapping.containsKey(entry.getKey())){
                continue;
            }
            int index = handler.paramIndexMapping.get(entry.getKey());
            paramValues[index] = convert(paramTypes[index], value);
        }

        if(handler.paramIndexMapping.containsKey(HttpServletRequest.class.getName())){
            int index = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[index] = req;
        }
        if(handler.paramIndexMapping.containsKey(HttpServletResponse.class.getName())){
            int index = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[index] = resp;
        }

        Object returnValue = handler.method.invoke(handler.controller, paramValues);
        if(returnValue == null || returnValue instanceof Void){
            return;
        }
        resp.getWriter().write(returnValue.toString());

    }

    private Handler getHandler(HttpServletRequest req) {
        if(this.handlerList.isEmpty()){return null;}
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        uri = uri.replace(contextPath, "").replaceAll("/+", "/");
        for(Handler handler : this.handlerList){
            Matcher matcher = handler.getPattern().matcher(uri);
            if(!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }

    private Object convert(Class<?> type, String value){
        if(type == Integer.class){
            return Integer.valueOf(value);
        }else if(type == Double.class){
            return Double.valueOf(value);
        }
        return value;
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        //2、扫描相关类
        doScanner(configContexts.getProperty("scanPackage"));
        //3、初始化扫描的类，并且将实例放入到IOC容器中
        doInstance();
        //4、依赖注入
        doAutowired();
        //5、初始化HandlerMapping
        initHandlerMapping();
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream is = null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
            this.configContexts.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //扫描相关类
    private void doScanner(String scanPackage) {
        URL url = null;
        url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());
        for(File file : classPath.listFiles()){
            if(file.isDirectory()){
                doScanner(scanPackage + "." + file.getName());
            }else{
                if(!file.getName().endsWith(".class")){
                    continue;
                }
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }

        }

    }
    //初始化扫描的类，并且将实例放入到IOC容器中
    private void doInstance() {
        if(classNames.isEmpty()){
            return;
        }
        try {
            for(String className : classNames){
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(GPController.class)){
                    Object obj = clazz.newInstance();
                    String beanName = toLowerFirstCase(clazz.getName());
                    ioc.put(beanName, obj);
                }else if(clazz.isAnnotationPresent(GPService.class)){
                    GPService gpService = clazz.getAnnotation(GPService.class);
                    String beanName = "";
                    if("".equals(gpService.value())){
                        beanName = toLowerFirstCase(clazz.getName());
                    }else{
                        beanName = gpService.value();
                    }
                    Object obj = clazz.newInstance();
                    ioc.put(beanName, obj);
                    for(Class i : clazz.getInterfaces()){
                        if(ioc.containsKey(i.getName())){
                            throw new Exception("The" + i.getName() + "is exists!!");
                        }
                        ioc.put(i.getName(), obj);
                    }
                }
            }
        } catch (Exception e) {
                e.printStackTrace();
        }

    }

    //小写第一个字母
    private String toLowerFirstCase(String name) {
        char[] chars = name.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    //依赖注入
    private void doAutowired() {
        if(ioc.isEmpty()){
            return;
        }
        for(Map.Entry<String, Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for(Field field : fields){
                if(!field.isAnnotationPresent(GPAutowired.class)){continue;}
                String beanName = "";
                GPAutowired gpAutowired = field.getAnnotation(GPAutowired.class);
                if("".equals(gpAutowired.value())){
                    beanName = field.getName();
                }else{
                    beanName = gpAutowired.value();
                }
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(), beanName);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //初始化HandlerMapping
    private void initHandlerMapping() {
        if(ioc.isEmpty()){
            return;
        }
        for(Map.Entry<String, Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(GPController.class)){
                continue;
            }
            String beanUrl = "";
            if(clazz.isAnnotationPresent(GPRequestMapping.class)){
                GPRequestMapping gpRequestParam = clazz.getAnnotation(GPRequestMapping.class);
                beanUrl = gpRequestParam.value();
            }
            for(Method method : clazz.getMethods()){
                if(!method.isAnnotationPresent(GPRequestMapping.class)){
                    continue;
                }
                GPRequestMapping gpRequestMapping = method.getAnnotation(GPRequestMapping.class);
                String regex = ("/" + beanUrl + "/" + gpRequestMapping.value()).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                this.handlerList.add(new Handler(pattern, method, entry.getValue()));
                System.out.println("Mapped :" + pattern + "," + method);
            }
        }

    }

    public class Handler{
        private Pattern pattern;//正则
        private Method method;
        private Object controller;
        private Class<?>[] paramTypes;
        private Map<String, Integer> paramIndexMapping;

        public Handler(Pattern pattern, Method method, Object controller) {
            this.pattern = pattern;
            this.method = method;
            this.controller = controller;
            this.paramTypes = method.getParameterTypes();

            paramIndexMapping = new HashMap<String, Integer>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method) {
            Annotation[][] annotations = method.getParameterAnnotations();
            for(int i = 0; i < annotations.length; i ++){
                for(Annotation a : annotations[i]){
                    if(a instanceof GPRequestParam){
                        String paramName = ((GPRequestParam) a).value();
                        if(!"".equals(paramName.trim())){
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }
            Class<?>[] parameterTypes = method.getParameterTypes();
            for(int i = 0; i < parameterTypes.length; i ++){
                Class<?> type = parameterTypes[i];
                if(type == HttpServletRequest.class ||
                        type == HttpServletResponse.class){
                    paramIndexMapping.put(type.getName(), i);
                }
            }
        }

        public Pattern getPattern() {
            return pattern;
        }

        public void setPattern(Pattern pattern) {
            this.pattern = pattern;
        }

        public Method getMethod() {
            return method;
        }

        public void setMethod(Method method) {
            this.method = method;
        }

        public Object getController() {
            return controller;
        }

        public void setController(Object controller) {
            this.controller = controller;
        }

        public Class<?>[] getParamTypes() {
            return paramTypes;
        }

        public void setParamTypes(Class<?>[] paramTypes) {
            this.paramTypes = paramTypes;
        }
    }

}
